package com.css.zfzx.sjcj.modules.fxpc.HddcA1Material.repository.impl;

import com.css.zfzx.sjcj.modules.fxpc.HddcA1Material.repository.HddcA1MaterialNativeRepository;
import com.css.zfzx.sjcj.modules.fxpc.qhDrill.repository.QhDrillNativeRepository;
import com.css.zfzx.sjcj.modules.pojo.QueryVo;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

/**
 * @Description: pc-statistics
 * @Author: lhl
 * @CreateDate: 2021/5/13 11:17
 */
@Repository
public class HddcA1MaterialNativeRepositoryImpl implements HddcA1MaterialNativeRepository {
    @PersistenceContext
    private EntityManager em;

    private static final Logger log = LoggerFactory.getLogger(HddcA1MaterialNativeRepositoryImpl.class);


    @Override
    public String count(QueryVo queryVo) {
        StringBuilder sql = new StringBuilder("select count(*) from hddc_a1_invrgnhasmaterialtable");
        StringBuilder whereSql = new StringBuilder(" where 1=1 ");
        if (!StringUtils.isEmpty(queryVo.getProvince())) {
            whereSql.append(" and province = :province");
        }
        if (!StringUtils.isEmpty(queryVo.getCity())) {
            whereSql.append(" and city = :city");
        }
        if (!StringUtils.isEmpty(queryVo.getArea())) {
            whereSql.append(" and area = :area");
        }
        String startDate = queryVo.getStartTime();
        String endDate = queryVo.getEndTime();
        // 时间段
        if (StringUtils.isNotEmpty(startDate)) {
            whereSql.append(" and substring(create_time,1,10) >= :start");
        }
        if (StringUtils.isNotEmpty(endDate)) {
            whereSql.append(" and substring(create_time,1,10) <= :end");
        }
        if(queryVo.getIsQuality()){//质检数据 4：人工质检通过
            whereSql.append(" and qualityinspection_status = '4'");
        }
        // 删除标识为1：有效
        whereSql.append(" and is_valid = 1");

       Query query = this.em.createNativeQuery(sql.append(whereSql).toString());

        if (!StringUtils.isEmpty(queryVo.getProvince())) {
            query.setParameter("province", queryVo.getProvince());
        }
        if (!StringUtils.isEmpty(queryVo.getCity())) {
            query.setParameter("city", queryVo.getCity());
        }
        if (!StringUtils.isEmpty(queryVo.getArea())) {
            query.setParameter("area", queryVo.getArea());
        }

        // 时间
        if (StringUtils.isNotEmpty(endDate)) {
            query.setParameter("start", startDate);
        }
        if (StringUtils.isNotEmpty(startDate)) {
            query.setParameter("end", endDate);
        }
        String count = String.valueOf(query.getSingleResult());
        return count;
    }
}
